import os
from django.conf import settings as django_settings

DEFAULT = {
    'SECRET_ID': os.environ.get('TX_SECRET_ID'),
    'SECRET_KEY': os.environ.get('TX_SECRET_KEY'),
    'SMS_SDK_APPID': '1400909639',
    'SIGN_NAME': 'lea4ningtop网',
    'TEMPLATE_ID': '2152168',
}

# from utils.loggers import log_uru
#
# log_uru.error(DEFAULT)


class TxSMSSettings:
    def __init__(self, defaults=None, user_settings=None):
        '''
        初始化配置参数
        :param defaults:默认参数
        :param user_settings: 用户定义在项目配置文件中的设置
        '''
        if user_settings:
            self._user_settings = user_settings
        self.defaults = defaults or DEFAULT  # 默认配置

    @property
    def user_settings(self):
        if not hasattr(self, '_user_settings'):
            # 从django配置中获取指定的配置项
            self._user_settings = getattr(django_settings, 'TX_SMS_SETTINGS', {})
        return self._user_settings

    def __getattr__(self, attr):
        if attr not in self.defaults:
            # 如果配置项不是我锁指定的这些配置，抛出异常
            raise AttributeError("Invalid API setting: '%s'" % attr)
        try:
            # 从用户配置中查找
            val = self.user_settings[attr]
        except KeyError:
            # 如果用户配置中没有，就使用默认配置
            val = self.defaults[attr]
        return val


tx_sms_settings = TxSMSSettings()
